<template>
  <div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.username" style="width: 240px; margin-right: 10px" placeholder="请输入用户名查询" :prefix-icon="Search"></el-input>
      <el-input v-model="data.nickname" style="width: 240px; margin-right: 10px" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.collegeAdminList" stripe @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="adminId"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="名称" prop="nickname"></el-table-column>
        <el-table-column label="所属学院" prop="collegeName"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'success' : 'danger'">
              {{ scope.row.status == 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="role">
          <template #default="scope">
            <span v-if="scope.row.role === 'ADMIN'">院管理员</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" circle @click="handleUpdate(scope.row)"></el-button>
            <el-button type="danger" :icon="Delete" circle @click="del(scope.row.adminId)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination
          @current-change="load"
          @size-change="load"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
      />
    </div>

    <el-dialog title="院管理员信息" v-model="data.formVisible" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px 30px 0px 0px">
        <el-form-item label="用户名" prop="username">
          <el-input :disabled="data.form.adminId" v-model="data.form.username" autocomplete="off" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="名称" prop="nickname">
          <el-input v-model="data.form.nickname" autocomplete="off" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="所属学院" prop="collegeId">
          <el-select style="width: 100%" v-model="data.form.collegeId" placeholder="请选择所属学院">
            <el-option
                v-for="item in data.collegeList"
                :key="item.collegeId"
                :label="item.name"
                :value="item.collegeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="data.form.status">
            <el-radio v-for="item in collegeAdminStatus" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select style="width: 100%" v-model="data.form.role" disabled>
            <el-option value="ADMIN" label="院管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import alovaInstance from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Search} from "@element-plus/icons-vue";

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  form: {},
  collegeAdminList: [],
  username: '',
  nickname: '',
  collegeList:[],
  ids:[],
  rules: {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    nickname: [
      { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    collegeId: [
      { required: true, message: '请选择所属学院', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'blur' }
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'blur' }
    ]
  },
})
const formRef = ref();
const collegeAdminStatus = ref([
  { label: '启用', value: '0' },
  { label: '禁用', value: '1' },
])

const loadCollegeList = () => {
  alovaInstance.Get('/sysAdminCollege/selectAll').then(res => {
    if (res.code === '200') {
      data.collegeList = res.data
    }
  })
}

// 分页查询
const load = () => {
  alovaInstance.Get('/collegeAdmin/selectPage', {
    params: {
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      username: data.username,
      nickname: data.nickname
    }
  }).then(res => {
    if (res.code === '200') {
      data.collegeAdminList = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
}

//重置输入框操作方法
const reset = () =>{
  data.username = '',
  data.nickname = ''
  //重新渲染数据
  load()
}

//新增操作
const handleAdd = () =>{
  //显示新增对话框
  data.formVisible = true
  //防止有脏数据
  data.form ={}
  data.form.role = 'ADMIN'
  data.form.status = '0'
}

//更新（编辑）操作
const handleUpdate = (row) =>{
  //深拷贝一个新的对象用于编辑。这样就不会影响行对象
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

//对话框的保存按钮事件
const save = () =>{
  formRef.value.validate((valid)=>{
    //通过校验才能点击更新或新增的保存操作
    if(valid){
      //有id进行更新操作。无id进行新增操作
      data.form.adminId ? update() : add()
    }
  })
}

// 新增（保持不变）
const add = () => {
  data.form.createBy = data.user.username
  alovaInstance.Post('/collegeAdmin/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 更新（修复）
const update = () => {
  data.form.updateBy = data.user.username
  alovaInstance.Put('/collegeAdmin/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 删除（修改URL路径）
const del = (adminId) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdmin/deleteCollegeAdmin/${adminId}/${data.user.username}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

// 批量选择（保持不变）
const handleSelectionChange = (rows) =>{  //返回选中的行对象数组
  console.log(rows)
  //从选中的行对象中取出所有的id，组成一个新数组！
  //使用map函数(数组内置函数)
  //遍历rows数组，将每个元素（行对象）的id属性值提取出来，组成一个新的数组。并赋值给存储id的数组中
  data.ids = rows.map(row => row.adminId)
  console.log(data.ids)
}

// 批量删除（修改URL路径）
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选中需删除的数据')
    return
  }
  ElMessageBox.confirm('批量删除数据后无法恢复，您确认删除吗？', '批量删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdmin/deleteCollegeAdminBatch/${data.user.username}`, data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

loadCollegeList()
load()

</script>